# -- coding: utf-8 --
# just specify the encoding of the python file
import urllib2
import urllib
import re
import csv

def LogMissingSong(msg):
    FILE=open('MissingList.txt','a')
    FILE.write(msg+'\n')
    
def buildKeywords(songName, singerName):    
    queryString = '%s %s' % (songName, singerName)
    queryString = queryString.strip().encode('UTF_8')
    _keywords = urllib.urlencode({'key':queryString})
    return _keywords


def getURI(songName, singerName):
    print 'Begin to query: ', songName            
    _keywords = buildKeywords(songName, singerName)

    # add the proxy if necessary
    _proxy = urllib2.ProxyHandler({'http':'web-proxy.chn.hp.com:8088'})
    _opener = urllib2.build_opener(_proxy)
    _opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3')]  
    urllib2.install_opener(_opener)
    
    
    searchUrl = 'http://ting.baidu.com/search?' + _keywords
    print 'Combined Search Url: %s' % searchUrl    
    print 'Fetch the content of Search Url, find the first song id in the search results... '

    f = urllib2.urlopen(searchUrl)
    responseString = f.read()
    f.close()
#    print responseString        
 
    #find the first song's id in rearch result 
    m = re.search('sid.*;', responseString)
    if m is not None:
        responseString = m.group(0)
    else:
        LogMissingSong('%s, %s'% (songName,singerName))
        return ""    
        
    resourceUrl=""
    m = re.search('\d{1,}', responseString)    
    if m is not None:
        resourceUrl = 'http://ting.baidu.com/song/%s/download' % re.search('\d*', m.group(0)).group(0)
    else:
        LogMissingSong('%s, %s'% (songName,singerName))
        return ""
    
    print 'Where the mp3 file locates: %s ' % resourceUrl
    
    f = urllib2.urlopen(resourceUrl)
    responseString = f.read()
#    print responseString
    f.close()

    m = re.search('/data/music.*?mp3', responseString)
    downloadURI = 'http://ting.baidu.com' + m.group(0)        
    
    print "Finish querying..."
    return downloadURI


if __name__ == '__main__':
    FILE = open('ResourceURI.txt',"w")
    songReader = csv.reader(open('dbFM.csv', 'rb'), delimiter=',')
    ignoreflag = 0
    for song, singer in songReader:
        if song != '':
            print song, singer
            FILE.write(getURI(song, singer)+"\n")
    
#    print getURI('Song Bird', 'Eva Cassidy')    
#    print getURI('808', '郑秀文')
#    print getURI('再见', '张震岳')
#    print getURI('A Whiter Shade Of Pale', '侧田')
#    print getURI(' Close To You', 'The Carpenters')

 





